#include "base/net/net_pack_handle.h"
#include "base/core/com_define.h"

NetPackHandle::NetPackHandle()
  : m_count(0),
    m_handles(nullptr),
    m_handleNames(nullptr),
    m_service(nullptr),
    m_close(false) 
{}

NetPackHandle::~NetPackHandle() 
{}

bool NetPackHandle::Init(uint32_t count) 
{
    bool result = false;
    m_count  = count + 1;

    m_handles = new NetPackHandleFunc[m_count];
    MMOLOG_PROCESS_ERROR(m_handles);

    m_handleNames = new const char*[m_count];
    MMOLOG_PROCESS_ERROR(m_handleNames);

    Clear();

    result = true;
Exit0:
    if (!result) 
	{
        MMO_DELETE_ARRAY(m_handleNames);
        MMO_DELETE_ARRAY(m_handles);
    }
    return result;
}

void NetPackHandle::UnInit() 
{
    MMO_DELETE_ARRAY(m_handles);
    MMO_DELETE_ARRAY(m_handleNames);

    m_count = 0;
    m_service = nullptr;
}

void NetPackHandle::Clear() 
{
    MMOLOG_ASSERT(m_handles != nullptr);
    MMOLOG_ASSERT(m_handleNames != nullptr);
    for (uint32_t i = 0; i < m_count; ++i) 
	{
        m_handles[i] = nullptr;
        m_handleNames[i] = nullptr;
    }
}

void NetPackHandle::Close() 
{
    m_close = true;
}

bool  NetPackHandle::RegisteNetPackHandle(uint32_t cmd, NetPackHandleFunc handle, const char* handleName) 
{
	MMOLOG_ASSERT(handle);
	MMOLOG_ASSERT(cmd < m_count);
	MMOLOG_ASSERT(m_handles[cmd] == NULL);

	m_handles[cmd] = handle;
	m_handleNames[cmd] = handleName;
	return true;
}

NetPackHandleFunc NetPackHandle::GetNetPackHandle(uint32_t cmd) 
{
	if (m_close) 
	{
		return NULL;
	}
	if (cmd < m_count) 
		return m_handles[cmd];
	else
		return NULL;
}

const char* NetPackHandle::GetNetPackHandleName(uint32_t cmd) 
{
    if (cmd < m_count)
        return m_handleNames[cmd];
    else
        return NULL;
}

void NetPackHandle::BindService(void* service) 
{
    MMOLOG_ASSERT(service != nullptr);
    m_service = service;
}

void* NetPackHandle::GetService()
{
    return m_service;
}
